<template>
  <div v-loading="queueLoading || loading.pager" ref="containerRef" class="add-product-container">
    <div class="header">
      <div class="title">
        <span>{{ $t("goods_archive.add_goods") }}{{ !!typeTitle ? ` - ${typeTitle}` : "" }}</span>
        <div class="anchor">
          <template v-for="[name, item] in Object.entries(blocks)">
            <el-button v-if="!item.hide" :class="{ active: false }" link @click="handleAnchor(name as BlockNames)">
              {{ item.title }}
            </el-button>
          </template>
        </div>
      </div>
      <div class="handle">
        <el-button @click="emits('close', saved)">{{ $t("merak.cancel") }}</el-button>
        <el-button type="primary" plain @click="handleSave(true)">{{ $t("merak.save_continue") }}</el-button>
        <el-button type="primary" :loading="loading.button" @click="handleSave()">{{ $t("merak.save") }}</el-button>
        <el-icon @click="emits('close', saved)">
          <Close />
        </el-icon>
      </div>
    </div>
    <div class="content">
      <el-scrollbar ref="scrollRef" @scroll="handleScroll">
        <el-form ref="formRef" label-position="top" label-width="auto" :model="formValue">
          <MerakCollapse v-model="collapseActive">
            <MerakCollapseItem
              v-if="!blocks[BlockNames.basic].hide"
              :name="BlockNames.basic"
              :title="blocks[BlockNames.basic].title"
            >
              <!-- 基本信息 -->
              <Basic
                ref="basicRef"
                v-model="formValue"
                :id="typeId"
                :span="span"
                :items="formItems[BlockNames.basic]"
                :editor="editor"
                :suite="props.suite"
                @render-color="colors => (spmColors = colors)"
                @render-spu="spu => (sku_before = spu)"
                @render-size-standard="size => (sizeStandard = size)"
                @change-required="clearRef?.setRequired"
              />
            </MerakCollapseItem>
            <MerakCollapseItem
              v-if="!blocks[BlockNames.specs].hide"
              :name="BlockNames.specs"
              :title="blocks[BlockNames.specs].title"
            >
              <!-- 规格信息 -->
              <Specs
                ref="specRef"
                v-model="formValue"
                :formConfig="formConfig"
                :specsInitial="specsInitial"
                :id="typeId"
                :suite="props.suite"
                :span="span"
                :spmColors="spmColors"
                :sku_before="sku_before"
                :sizeStandard="sizeStandard"
                @change="handleSpcesChange"
              />
            </MerakCollapseItem>
            <MerakCollapseItem
              v-if="!blocks[BlockNames.clear].hide"
              :name="BlockNames.clear"
              :title="blocks[BlockNames.clear].title"
            >
              <!-- 清关属性 -->
              <Clear
                ref="clearRef"
                v-model="formValue"
                :id="typeId"
                :span="span"
                :items="formItems[BlockNames.clear]"
                :editor="editor"
                :suite="props.suite"
                @change-required="basicRef?.setRequired"
              />
            </MerakCollapseItem>
            <MerakCollapseItem
              v-if="!blocks[BlockNames.sale].hide"
              :name="BlockNames.sale"
              :title="blocks[BlockNames.sale].title"
            >
              <!-- 销售属性 -->
              <Sale
                ref="saleRef"
                v-model="formValue"
                :id="typeId"
                :span="span"
                :items="formItems[BlockNames.sale]"
                :editor="editor"
                :suite="props.suite"
              />
            </MerakCollapseItem>
            <MerakCollapseItem
              v-if="!blocks[BlockNames.picture].hide"
              :name="BlockNames.picture"
              :title="blocks[BlockNames.picture].title"
            >
              <template #title>
                <span>{{ blocks[BlockNames.picture].title }}</span>
                <span class="add-product-upload-text">{{ $t("goods_archive.upload_picture_text") }}</span>
              </template>
              <!-- 商品图片 -->
              <Picture
                ref="pictureRef"
                v-if="!queueLoading"
                :key="`picture_${dateNow}`"
                :id="typeId"
                :data="specsData"
                :valid="!!formConfig.has_color || !!formConfig.has_size"
              />
            </MerakCollapseItem>
            <MerakCollapseItem :name="BlockNames.video" :title="blocks[BlockNames.video].title">
              <template #title>
                <span>{{ blocks[BlockNames.video].title }}</span>
                <span class="add-product-upload-text">{{ $t("goods_archive.upload_video_text") }}</span>
              </template>
              <!-- 商品视频 -->
              <Video ref="videoRef" v-if="!queueLoading" :key="`video_${dateNow}`" :id="typeId" />
            </MerakCollapseItem>
          </MerakCollapse>
        </el-form>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup lang="ts" name="add-product-container">
import type { MerakControlProps } from "@/components/MerakControl";

import { getCurrentInstance, ref, reactive, computed, onMounted } from "vue";

import useLoading from "@/hooks/useLoading";

import { useGlobalStore } from "@/stores/modules/global";

import { ElButton, ElScrollbar, ElForm, ElMessage, ElIcon } from "element-plus";
import { Close } from "@element-plus/icons-vue";

import { MerakCollapse, MerakCollapseItem } from "@/components/MerakCollapse";

import Basic from "./components/Basic.vue";
import Specs from "./components/Specs.vue";
import Clear from "./components/Clear.vue";
import Sale from "./components/Sale.vue";
import Picture from "./components/Picture.vue";
import Video from "./components/Video.vue";

import { ResultEnum } from "@/enums/httpEnum";
import { InitParams, getInitData, saveData } from "@/api/modules/goodsArchive/addGoodsArchive";

import { confirmWarningMsg } from "@/utils/messageUtils";

const enum BlockNames {
  basic = "basic",
  specs = "specs",
  clear = "clear",
  sale = "sale",
  picture = "picture",
  video = "video"
}

const props = defineProps<{
  id: string | number; // type_id
  title: string;
  suite: 0 | 1; // 是否套件
  copyData: {
    // 复制创建的商品信息
    type_id?: string | number;
    type_title?: string;
    product_id?: string | number;
  };
}>();

const emits = defineEmits<{
  close: [saved: boolean];
}>();

const currentInstance = getCurrentInstance();

const { queueId, queueLoading } = useLoading();

const { language } = useGlobalStore();

const containerRef = ref<HTMLDivElement>();

const formRef = ref<InstanceType<typeof ElForm>>();

const scrollRef = ref<InstanceType<typeof ElScrollbar>>();

const basicRef = ref<InstanceType<typeof Basic>>();

const clearRef = ref<InstanceType<typeof Basic>>();

const saleRef = ref<InstanceType<typeof Basic>>();

const specRef = ref<InstanceType<typeof Specs>>();

const pictureRef = ref<InstanceType<typeof Picture>>();

const videoRef = ref<InstanceType<typeof Video>>();

// 标题激活
const activeTitle = ref<BlockNames>(BlockNames.basic);

// 时间戳
const dateNow = ref<number>();

// 是否编辑
const editor = ref(false);

// 商家颜色
const spmColors = ref();

// 系统货号前缀(系统型号)
const sku_before = ref();

// 码制
const sizeStandard = ref();

// 是否有存储
const saved = ref(false);

// 规格联动数据
const specsData = ref<any>();

const loading = reactive({
  button: false,
  pager: false
});

// 表单项配置
// "has_color"  //是否有颜色 0 - 否 1 - 是
// "has_size" //是否有规格 0 - 否 1 - 是
// "package_type"  //套装格式 0 - 无 1 - 单尺码 2 - 多尺码
// "has_gender"  //是否有性别 0 否 1 是
// "spec_type"  //规格 1 - 文本 2 - 枚举
const formConfig = reactive<Record<string, any>>({});

// 当前展开块
const collapseActive = reactive<BlockNames[]>([
  BlockNames.basic,
  BlockNames.specs,
  BlockNames.clear,
  BlockNames.sale,
  BlockNames.picture,
  BlockNames.video
]);

// 规格初始化数据
const specsInitial = reactive<Record<string, any>>({});

// 表单项数据
const formItems = reactive<Record<string, MerakControlProps[]>>({
  [BlockNames.basic]: [],
  [BlockNames.clear]: [],
  [BlockNames.sale]: []
});

// 表格数据
const formValue = reactive<Record<string, any>>({});

// 商品 ID
const typeId = computed(() => props.copyData.type_id ?? props.id);

// 商品品名
const typeTitle = computed(() => props.copyData.type_title ?? props.title);

// 展示块
const blocks = computed<Record<BlockNames, { title?: string; hide?: boolean }>>(() => ({
  [BlockNames.basic]: {
    title: currentInstance?.proxy?.$t("goods_archive.edit_base_info"),
    hide: formItems[BlockNames.basic].length === 0
  },
  [BlockNames.specs]: {
    title: currentInstance?.proxy?.$t("goods_archive.art_no_info"),
    hide: !formConfig.has_color && !formConfig.has_size
  },
  [BlockNames.clear]: {
    title: currentInstance?.proxy?.$t("goods_archive.customs_clearance_attr"),
    hide: formItems[BlockNames.clear].length === 0
  },
  [BlockNames.sale]: {
    title: currentInstance?.proxy?.$t("goods_archive.sales_attr"),
    hide: formItems[BlockNames.sale].length === 0
  },
  [BlockNames.picture]: {
    title: currentInstance?.proxy?.$t("goods_archive.goods_picture"),
    hide: !!formConfig.has_size && (!!formConfig.has_color ? !specsData.value : true)
  },
  [BlockNames.video]: { title: currentInstance?.proxy?.$t("goods_archive.goods_video") }
}));

// 表格项自适应列数
const span = computed(() => (language === "zh" ? 6 : 8));

// 锚点滚动
const handleAnchor = (name: BlockNames) => {
  const node = containerRef.value?.querySelector(`[data-name=${name}]`);
  activeTitle.value = name;
  if (!node) return;
  node.scrollIntoView({ behavior: "smooth" });
};

// 滚动条事件
const handleScroll = () => {
  basicRef.value?.closePanel();
  clearRef.value?.closePanel();
  saleRef.value?.closePanel();
};

// 规格触发事件
const handleSpcesChange = (data: any) => {
  specsData.value = JSON.parse(JSON.stringify(data));
};

// 保存
const handleSave = (keep: boolean = false) => {
  const customValidate = () => {
    return new Promise<{
      ref?: InstanceType<typeof ElForm>;
      err?: string;
      other?: boolean;
    }>(resolve => {
      formRef.value
        ?.validate()
        .then(() => {
          resolve({});
        })
        .catch(error => {
          resolve({ ref: formRef.value, err: Object.keys(error)?.[0] });
        });
    });
  };
  loading.button = true;
  Promise.all([specRef.value?.validate(), customValidate()]).then(arr => {
    const baseError = arr
      .filter(Boolean)
      .find(item => !item?.other && formItems[BlockNames.basic].some(formItem => formItem.field === item?.err));
    const lastError = arr.filter(Boolean).find(item => !item?.other);
    const otherError = arr.filter(Boolean).find(item => !!item?.other);
    loading.button = false;
    if (!!baseError?.err) {
      baseError.ref?.scrollToField(baseError.err!);
    } else if (!!otherError?.err) {
      otherError.ref?.scrollToField(otherError.err!);
    } else if (!!lastError?.err) {
      lastError.ref?.scrollToField(lastError.err!);
    } else {
      loading.button = true;
      pictureRef.value?.getImgsData();
      Promise.all([
        specRef.value?.get_postdata(formValue.cc_model),
        pictureRef.value?.getImgsData(),
        videoRef.value?.getVedioData()
      ]).then(([specData, pictureData, videoData]) => {
        loading.button = false;
        if ((!!formConfig.has_color || !!formConfig.has_size) && !specData) return;
        const params: Record<string, any> = {
          base: { ...formValue, type_id: typeId.value }
        };
        // 删除商品ID
        delete params.base.product_id;
        delete params.base.goods_id;
        // 判断是否存在系统货号或者型号
        if (!!formItems[BlockNames.basic].some(item => item.field === "spu")) {
          params.base.spu = `${sku_before.value}`;
        } else if (!!formItems[BlockNames.basic].some(item => item.field === "sku")) {
          params.base.sku = `${sku_before.value}`;
        }
        // 规格数据
        if (!!specData) {
          for (let index = 0; index < specData.length; index++) {
            const element = specData[index];
            console.log(element);
            if (!!element.sku) {
              element["sku"] = `${sku_before.value}` + "-" + element.sku;
            } else {
              element["sku"] = `${sku_before.value}`;
            }
          }
          params.spec = specData;
        }
        // 商品图片
        if (!!pictureData?.length) {
          params.image = [...(pictureData ?? [])];
        }
        // 商品视频
        if (!!videoData && !!Object.keys(videoData).length) {
          params.video = { ...(videoData ?? {}) };
        }
        confirmWarningMsg({
          msg: currentInstance?.proxy?.$t("goods_archive.add_goods_message") ?? "",
          callback: (status: string) => {
            if (status === "confirm") {
              loading.pager = true;
              saveData(params).then(({ code, message }) => {
                if (code == ResultEnum.SUCCESS) {
                  saved.value = true;
                  loading.pager = false;
                  ElMessage.success(currentInstance?.proxy?.$t("goods_archive.add_goods_success"));
                  if (keep) {
                    dateNow.value = Date.now();
                    formRef.value?.resetFields();
                    Object.keys(formValue).forEach(key => {
                      delete formValue[key];
                    });
                    // 清除基础信息
                    basicRef.value?.recombReduction();
                    // 清除清关信息
                    clearRef.value?.recombReduction();
                    // 清除企发信息
                    saleRef.value?.recombReduction();
                    // 清除规格信息
                    specRef.value?.resetSpec();
                    sku_before.value = undefined;
                    // 清除商品图片
                    specsData.value = [{ value: 0 }];
                    pictureRef.value?.reset();
                    // 清除商品视频
                    videoRef.value?.resetVedio();
                    // 滚动到最顶部
                    scrollRef.value?.setScrollTop(0);
                  } else {
                    emits("close", saved.value);
                  }
                } else {
                  const msg = typeof message === "string" ? message : Object.values(message)?.[0];
                  ElMessage.error(msg);
                }
              });
            }
          }
        });
      });
    }
  });
};

// 初始化
onMounted(() => {
  const params: InitParams = {
    type_id: typeId.value,
    is_suite: props.suite
  };
  if (!!props.copyData.product_id) {
    params.product_id = props.copyData.product_id;
  }
  getInitData(params, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      Object.assign(specsInitial, { ...(data.spec ?? {}) });
      Object.assign(formConfig, { ...(data.config ?? {}) });
      formItems.basic = [...(data.info ?? [])];
      formItems.clear = [...(data.cc_info ?? [])];
      formItems.sale = [...(data.qf_info ?? [])];
      if (!!data.form_value) {
        editor.value = true;
        Object.assign(
          formValue,
          { ...(data.form_value.info ?? {}) },
          { ...(data.form_value.cc_info ?? {}) },
          { ...(data.form_value.qf_info ?? {}) }
        );
      }
    }
  });
});
</script>

<style scoped lang="scss">
.add-product-container {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  color: var(--merak-text-color);
  font-size: var(--merak-text-size);
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: var(--merak-padding);
    background-color: var(--el-bg-color);
    border-radius: var(--merak-rounded);
    .title {
      & > span {
        font-size: 16px;
      }
      .anchor {
        padding-top: var(--merak-space);
        .el-button {
          margin: 0;
          padding: 0;
          min-width: auto;
          border: none;
          &:not(:first-child)::before {
            content: "·········";
            color: var(--merak-text-color) !important;
            margin: 0 var(--merak-space);
            cursor: default;
          }
          &.active,
          &:hover {
            color: var(--el-color-primary) !important;
          }
        }
      }
    }
    .handle {
      display: flex;
      align-items: center;
      .el-icon {
        margin-left: 23px;
        font-size: 16px;
        cursor: pointer;
      }
    }
  }
  .content {
    flex: 1;
    min-height: 0;
    padding-top: var(--merak-space);
    :deep(.merak-collapse-item--body-wrapper) {
      padding: var(--merak-space) 28px;
    }
  }
  .add-product-upload-text {
    margin-left: var(--merak-space);
    color: #a0a3a9;
    font-size: 12px;
  }
  :deep(.require_tip) {
    display: none;
  }
}
</style>
